package com.linxz.ui.transhlucentbar;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.linxz.ui.GuiHelper;
import com.linxz.ui.R;

/**
 * @author Linxz
 * 创建日期：2019年06月06日 08:40
 * version：v4.0.1
 * 描述：
 */
public class TranslucentRecycleView extends RecyclerView {
    static final String TAG = "TranslucentRecycleView";
    //伸缩视图
    private View zoomView;
    //伸缩视图初始高度
    private int zoomViewInitHeight = 0;
    // 记录首次按下位置
    private float mFirstPosition = 0;
    // 是否正在放大
    private Boolean mScaling = false;

    //渐变的视图
    private View transView;
    //渐变颜色
    private int transColor = Color.WHITE;
    //渐变开始位置
    private int transStartY = 50;
    //渐变结束位置
    private int transEndY = 300;

    //渐变开始默认位置，Y轴，50dp
    private final int DFT_TRANSSTARTY = 50;
    //渐变结束默认位置，Y轴，300dp
    private final int DFT_TRANSENDY = 200;

    private TranslucentRecycleChangedListener translucentChangedListener;

    public interface TranslucentRecycleChangedListener {
        /**
         * 透明度变化，取值范围0-255
         *
         * @param transAlpha
         */
        void onTranslucentChanged(int transAlpha);
    }

    public TranslucentRecycleView(Context context) {
        super(context);
    }

    public TranslucentRecycleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TranslucentRecycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setTranslucentChangedListener(TranslucentRecycleChangedListener translucentChangedListener) {
        this.translucentChangedListener = translucentChangedListener;
        addOnScrollListener(mOnScrollListener);
    }

    /**
     * 设置伸缩视图
     *
     * @param zoomView
     */
    public void setPullZoomView(View zoomView) {
        this.zoomView = zoomView;
        zoomViewInitHeight = zoomView.getLayoutParams().height;
        if (zoomViewInitHeight == FrameLayout.LayoutParams.MATCH_PARENT || zoomViewInitHeight == WindowManager.LayoutParams.WRAP_CONTENT) {
            zoomView.post(new Runnable() {
                @Override
                public void run() {
                    zoomViewInitHeight = TranslucentRecycleView.this.zoomView.getHeight();
                }
            });
        }
    }

    /**
     * 设置渐变视图
     *
     * @param transView 渐变的视图
     */
    public void setTransView(View transView) {
        setTransView(transView, getResources().getColor(R.color.white), GuiHelper.dip2px(getContext(), DFT_TRANSSTARTY), GuiHelper.dip2px(getContext(), DFT_TRANSENDY));
    }

    /**
     * 设置渐变视图
     *
     * @param transView  渐变的视图
     * @param transColor 渐变颜色
     * @param transEndY  渐变结束位置
     */
    public void setTransView(View transView, @ColorInt int transColor, int transStartY, int transEndY) {
        this.transView = transView;
        //初始视图-透明
        this.transView.setBackgroundColor(ColorUtils.setAlphaComponent(transColor, 0));
        this.transStartY = transStartY;
        this.transEndY = transEndY;
        this.transColor = transColor;
        if (transStartY > transEndY) {
            throw new IllegalArgumentException("transStartY 不得大于 transEndY .. ");
        }
    }

    private int tempScrollY;
    private int transAlpha;
    /**
     * 获取透明度
     *
     * @return
     */
    private int getTransAlpha() {
        //float scrollY = getScrollY();
        int scrollY =getScollYDistance();
        if (scrollY>=tempScrollY){
            //往下滑动
            if (transAlpha == 255){
                return transAlpha;
            }
        }
        tempScrollY=scrollY;
        Log.d(TAG, "[scrollY .. in]" + scrollY);
        if (transStartY != 0) {
            if (scrollY <= transStartY) {
                Log.d(TAG, "[getTransAlpha .. in ], 0透明度 == " + 0);
                return 0;
            } else if (scrollY >= transEndY) {
                Log.d(TAG, "[getTransAlpha .. in ], 1透明度 == " + 255);
                return 255;
            } else {
                int alpha=(int) ((scrollY - transStartY) / (transEndY - transStartY) * 255);
                Log.d(TAG, "[getTransAlpha .. in ], 2透明度 == " + alpha);
                return alpha;
            }
        } else {
            if (scrollY >= transEndY) {
                Log.d(TAG, "[getTransAlpha .. in ], 3透明度 == " + 255);
                return 255;
            }
            int alpha=(int) ((transEndY - scrollY) / transEndY * 255);
            Log.d(TAG, "[getTransAlpha .. in ], 4透明度 == " + alpha);
            return alpha;
        }
    }


    private int headerViewHeight=0;
    /**
     * 获取RecycleView滑动距离（只对LinearLayoutManager有效）
     * */
    public int getScollYDistance() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) this.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        int totalHeight=(position) * itemHeight;
        if (position == 0){
            headerViewHeight = itemHeight;
        }else{
            totalHeight = headerViewHeight+((position-1)*itemHeight);
        }
        int top=firstVisiableChildView.getTop();
        return totalHeight - top;
    }

    /**
     * 重置ZoomView
     */
    private void resetZoomView() {
        final ViewGroup.LayoutParams lp = zoomView.getLayoutParams();
        final float h = zoomView.getLayoutParams().height;// ZoomView当前高度

        // 设置动画
        ValueAnimator anim = ObjectAnimator.ofFloat(0.0F, 1.0F).setDuration(200);

        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                lp.height = (int) (h - (h - zoomViewInitHeight) * cVal);
                zoomView.setLayoutParams(lp);
            }
        });
        anim.start();
    }

    private OnScrollListener mOnScrollListener=new OnScrollListener(){
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
             transAlpha = getTransAlpha();
            if (transView != null) {
                Log.d(TAG, "[onScrollChanged .. in ], 透明度 == " + transAlpha);
                transView.setBackgroundColor(ColorUtils.setAlphaComponent(transColor, transAlpha));
            }
            if (translucentChangedListener != null) {
                translucentChangedListener.onTranslucentChanged(transAlpha);
            }
        }
    };


//    @Override
//    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
//        super.onScrollChanged(l, t, oldl, oldt);
//        int transAlpha = getTransAlpha();
//
//
//    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (zoomView != null) {
            ViewGroup.LayoutParams params = zoomView.getLayoutParams();
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    //手指离开后恢复图片
                    mScaling = false;
                    resetZoomView();
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (!mScaling) {
                        if (getScollYDistance() == 0) {
                            mFirstPosition = event.getY();
                        } else {
                            break;
                        }
                    }
                    mScaling = true;
                    int distance = (int) ((event.getY() - mFirstPosition) * 0.6);
                    if (distance < 0) {
                        break;
                    }
                    params.height = zoomViewInitHeight + distance;
                    Log.d(TAG, "params.height == " + params.height + ", zoomViewInitHeight == " + zoomViewInitHeight + ", distance == " + distance);
                    zoomView.setLayoutParams(params);
                    return true;
            }
        }
        return super.onTouchEvent(event);
    }
}
